package com.itheima.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingMapper;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderInfo;
import com.itheima.pojo.OrderSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderSettingMapper orderSettingMapper;

    @Autowired
    OrderDao orderDao;

    @Autowired
    MemberDao memberDao;

    // synchronized Lock 属于悲观锁
    // 使用乐观锁  在数据库加一个 int 类型的version字段
    @Override
    public  Result submit(OrderInfo orderInfo) {
        Date orderDate = orderInfo.getOrderDate();
        String telephone = orderInfo.getTelephone();
        String idCard = orderInfo.getIdCard();
        String name = orderInfo.getName();
        String orderType = orderInfo.getOrderType();
        Integer sex = orderInfo.getSex();
        Integer setmealId = orderInfo.getSetmealId();
        Integer id = orderInfo.getMemberId();//会员编号id
        //1、是否存在预约设置
        OrderSetting orderSetting = orderSettingMapper.findByDate(orderDate);
        if(orderSetting == null){
            return Result.ERROR("没有档期");
        }

        //2、判断是否约满
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if(number <= reservations){
           return Result.ERROR("约满");
        }

        //3、判断当前手机号码是否是会员
        Member member = memberDao.findByTelephone(telephone);
        //线程1 15601795090
        //线程2 15601795090
        //线程3 15601795090
        if(member == null){
            //4、自动注册
            member = new Member();
            member.setIdCard(idCard);
            member.setName(name);
            member.setSex(String.valueOf(sex));
            member.setRegTime(new Date());
            member.setPhoneNumber(telephone);
            memberDao.add(member);
        }
        Integer memberId = member.getId();

        //4、根据会员id 套餐id 预约日期查询是否存在预约
        Order query = new Order();
        query.setMemberId(memberId);
        query.setOrderDate(orderDate);
        query.setSetmealId(setmealId);

        List<Order> orders = orderDao.findByCondition(query);
        if(CollectionUtil.isNotEmpty(orders)){
            return Result.ERROR("请不要重复预约");
        }

        //选择家庭联系人 id要换一下
        if (id != null) {
            memberId = id;
        }
        //5、直接下单
        Order order = new Order();
        order.setSetmealId(setmealId);
        order.setOrderDate(orderDate);
        order.setMemberId(memberId);
        order.setOrderType(orderType);
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        orderDao.add(order);
        //线程1  version=0 100 99
        //线程2  version=0 100 99
        //线程3  version=0 100 99
        //6、更新已预约人数
        //大家先执行 update t_ordersetting set reservations = 0; 把默认更新为0
        int count = orderSettingMapper.updateReservations(orderSetting.getId(), orderSetting.getVersion());
        if(count == 0){
            throw new OptimisticLockingFailureException("更新失败");
        }

        return Result.OK("",order);//把order返回，页面需要订单id
    }

    @Override
    public Map findById(Integer id) {
        return orderDao.findById4Detail(id);
    }

    @Override
    public void updateOutTradeNo(Integer orderId, String outTradeNo) {
        orderDao.updateOutTradeNo(orderId,outTradeNo);
    }

    @Override
    public void updateOrderStatus(String out_trade_no) {
        orderDao.updateOrderStatus(out_trade_no);
    }
}
